Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

MkAdmonition

github Show source on GitHub

Admonition info box.

Examples

Example: Types

Note

Jinja

{{ "Different types." | MkAdmonition(typ="warning") }}

Note

Python

MkAdmonition(None, typ='warning')
Rendered

Warning

Different types.

Markdown
> [!WARNING]
> Different types.

Html
<div class="markdown-alert markdown-alert-warning">
<p class="markdown-alert-title">Warning</p>
<p>Different types.</p>
</div>

reST
.. warning:: 
    Different types.
GitHub
> [!WARNING]
> Different types.

Repr tree
MkAdmonition
╰── MkText('Different types.')

Example: Collapsible and expandable

Note

Jinja

{{ "Admonitions can also be collapsible." | MkAdmonition(collapsible=True, title="Expand me!", expanded=True) }}

Note

Python

MkAdmonition(None, title='Expand me!', collapsible=True, expanded=True)
Rendered
Expand me!

Admonitions can also be collapsible.

Markdown
<details open>
<summary>Expand me!</summary>

Admonitions can also be collapsible.

</details>

Html
<details open>
<summary>Expand me!</summary>
<p>Admonitions can also be collapsible.</p>
</details>

reST
.. info:: Expand me!
    Admonitions can also be collapsible.
GitHub
<details open>
<summary>Expand me!</summary>

Admonitions can also be collapsible.

</details>

Repr tree
MkAdmonition
╰── MkText('Admonitions can also be collapsible.')

Example: Inlined

Note

Jinja

{{ "Inlined" | MkAdmonition(inline="left") }}

Note

Python

MkAdmonition(None, inline='left')
Rendered

Note

Inlined

Markdown
> [!NOTE]
> Inlined

Html
<div class="markdown-alert markdown-alert-note">
<p class="markdown-alert-title">Note</p>
<p>Inlined</p>
</div>

reST
.. info:: 
    Inlined
GitHub
> [!NOTE]
> Inlined

Repr tree
MkAdmonition
╰── MkText('Inlined')
DocStrings

class MkAdmonition(mkcontainer.MkContainer)
Base classes
NameChildrenInherits
MkContainer
mknodes.basenodes.mkcontainer
A node containing other MkNodes.
⋔ Inheritance diagram
graph TD
  178616935["mkadmonition.MkAdmonition"]
  835538629["mkcontainer.MkContainer"]
  1956333208["mkcontainer.MkContainerBase"]
  1359323199["mknode.MkNode"]
  2751680898["builtins.object"]
  835538629 --> 178616935
  1956333208 --> 835538629
  1359323199 --> 1956333208
  2751680898 --> 1359323199
NodeFile

/home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mkadmonition/metadata.toml

[metadata]
icon = "octicon:info-16"
name = "MkAdmonition"

[requirements.extension.admonition]

[requirements.extension."pymdownx.details"]

[requirements.extension."pymdownx.superfences"]

[examples.annotations]
title = "Annotations"
python = """
import mknodes as mk
node = mk.MkAdmonition("MkAdmonitions can carry annotations(1).")
node.annotations[1] = "Super handy!"
node
"""

[examples.types]
title = "Types"
jinja = """
{{ "Different types." | MkAdmonition(typ="warning") }}
"""

[examples.collapsible]
title = "Collapsible and expandable"
jinja = """
{{ "Admonitions can also be collapsible." | MkAdmonition(collapsible=True, title="Expand me!", expanded=True) }}
"""

[examples.inlined]
title = "Inlined"
jinja = """
{{ "Inlined" | MkAdmonition(inline="left") }}
"""

[output.markdown]
template = """
{% if node.title or node.get_items() %}
{{ node.title_line }}
{{ node.get_items() | join(node.block_separator) | indent(first=True) }}
{% endif %}
"""

[output.block]
template = """
{{ node.fence_boundary }} admonition {{ node.typ }}{{ node.title | add(" | ") }}
{{ node.get_items() | join }}
{{ node.fence_boundary }}
"""

[output.rst]
template = """
.. {{ node.typ }}:: {{ node.title or "" }}
{{ node.get_items() | join(node.block_separator) | indent(first=True) }}
"""

Code

mknodes.basenodes.mkadmonition.MkAdmonition

class MkAdmonition(mkcontainer.MkContainer):
    """Admonition info box."""

    ICON = "octicons/info-16"
    ATTR_LIST_SEPARATOR = "    "
    REQUIRED_EXTENSIONS = [
        resources.Extension("admonition"),
        resources.Extension("pymdownx.details"),
        resources.Extension("pymdownx.superfences"),
    ]

    def __init__(
        self,
        content: str | list[mknode.MkNode] | mknode.MkNode,
        *,
        typ: datatypes.AdmonitionTypeStr | str = "info",
        title: str | None = None,
        collapsible: bool = False,
        expanded: bool = False,
        inline: Literal["left", "right"] | None = None,
        **kwargs: Any,
    ) -> None:
        """Constructor.

        Args:
            content: Admonition content
            typ: Admonition type
            title: Optional Admonition title
            collapsible: Whether Admontion can get collapsed by user
            expanded: Initial state if collapsible is set
            inline: Whether admonition should rendered as inline block
            kwargs: Keyword arguments passed to parent
        """
        self.typ = typ
        self.title = title
        self.collapsible = collapsible
        self.inline = inline
        self.expanded = expanded
        super().__init__(content=content, **kwargs)

    def attach_annotations(self, text: str) -> str:
        # we deal with attaching annotations ourselves.
        return text

    @property
    def title_line(self) -> str:
        block_start = "???" if self.collapsible else "!!!"
        if self.collapsible and self.expanded:
            block_start += "+"
        if self.inline:
            inline_label = " inline" if self.inline == "left" else " inline end"
        else:
            inline_label = ""
        ann_marker = " annotate" if self.annotations else ""
        title = f' "{self.title}"' if self.title is not None else ""
        optional = ann_marker + inline_label
        return f"{block_start} {self.typ}{optional}{title}"

    def get_content(self) -> resources.NodeContent:
        """Single-pass: get markdown with custom admonition formatting and resources."""
        items = self.get_items()
        if not items and not self.title:
            return resources.NodeContent(
                markdown="",
                resources=self._build_node_resources(),
            )

        # Collect content from children
        renderer = rendering.current()
        child_contents = [renderer.render_child(item) for item in items]
        child_markdowns = [content.markdown for content in child_contents]

        text = "\n".join(child_markdowns)
        indented = textwrap.indent(text, "    ")
        annotations = f"\n{self.annotations}\n" if self.annotations else ""
        md = f"{self.title_line}\n{indented}\n{annotations}"

        # Aggregate resources
        aggregated = self._build_node_resources()
        for child_content in child_contents:
            aggregated.merge(child_content.resources)

        return resources.NodeContent(markdown=md, resources=aggregated)

    def to_md_unprocessed(self) -> str:
        content = self.get_content()
        return content.markdown

Page info
Code for this page

mknodes.manual.nodes_section.create_section_for_nodes

def create_section_for_nodes(
    nav: mk.MkNav,
    klasses: Sequence[type[mk.MkNode]],
) -> mk.MkTable:
    table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
    for kls in klasses:
        tpl = "classpage_custom.jinja"
        page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
        nav += page
        if kls.STATUS:
            page.metadata.status = kls.STATUS
        elif kls.JS_FILES:
            page.metadata.status = "js"
        elif kls.CSS:
            page.metadata.status = "css"
        page.created_by = create_section_for_nodes
        link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
        extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
        table.add_row((link, kls.__doc__, extensions))
    return table

Resources
Resources(css=[],
          markdown_extensions={'admonition': {},
                               'pymdownx.details': {},
                               'pymdownx.highlight': {'anchor_linenums': True,
                                                      'line_spans': '__span',
                                                      'pygments_lang_class': True},
                               'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
                                                                           'format': <function fence_code_format at 0x7d707a397060>,
                                                                           'name': 'mermaid'}]},
                               'pymdownx.tabbed': {},
                               'tables': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
  source_function: create_section_for_nodes
  source_line_no: 93
hide:
- toc
icon: octicons/info-16
title: MkAdmonition